use std::fs::create_dir;
use mime::Name;
use actix_files::Files;
use futures::future::FutureExt;
use actix_session::{CookieSession, UserSession};
use actix_web::{
    //middleware::Logger,
    App,
    HttpServer,
    dev::Service,
    web::{get, resource, scope},
    http::header::DispositionType
};
use chrono::{Local, Datelike, Timelike};
#[macro_use]
mod rules;
mod login;
mod market;
mod system;
mod users;
mod util;

pub const CONTEXT_PATH: &str = "/pss";

fn mime_type(_file: &Name) -> DispositionType {
    DispositionType::Inline
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let _ = create_dir("./tmp");
    println!("程序启动成功");
    //std::env::set_var("RUST_LOG", "error");
    //std::env::set_var("RUST_BACKTRACE", "1");
    //env_logger::init();
    HttpServer::new(move || {
        let session = CookieSession::signed(&[0; 32]).secure(false);
        let files = Files::new("/js", "webapp/js/")
            .use_etag(false)
            .use_last_modified(false)
            .prefer_utf8(true)
            .mime_override(mime_type);
        let market_scope = scope("/market")
            .service(market::action::route_list)
            .service(market::action::route_data)
            .service(market::action::edit_route)
            .service(market::action::save_route)
            .service(market::action::print_route);
        let user_scope = scope("/users")
            .service(users::action::user_list)
            .service(users::action::user_data)
            .service(users::action::edit_user)
            .service(users::action::validate_user)
            .service(users::action::save_user)
            .service(users::action::users_reward_data)
            .service(users::action::edit_user_reward)
            .service(users::action::save_user_reward)
            .service(users::action::authorization)
            .service(users::action::ajax_authorization)
            .service(users::action::print_user)
            .service(users::action::export_user);
        let scope = scope(CONTEXT_PATH)
            .route("", get().to(login::action::index))
            .service(files)
            .service(login::action::imgs)
            .service(login::action::login)
            .service(login::action::main)
            .service(login::action::ajax_menu)
            .service(login::action::quit)
            .service(login::action::show_photo)
            .service(login::action::upload_file)
            .service(market_scope)
            .service(user_scope);
        App::new()
            .wrap(session)
            //.wrap(Logger::default())
            .wrap_fn(|req, srv| {
                let path = req.path();
                if path.contains(".html") {
                    let now = Local::now();
                    println!(
                        "-------- {:04}-{:02}-{:02} {:02}:{:02}:{:02} --------",
                        now.year(),
                        now.month(),
                        now.day(),
                        now.hour(),
                        now.minute(),
                        now.second()
                    );
                    println!("Url : {} {}", req.method(), path);
                    println!("Parameters : {:?}", req.query_string());
                    println!("-------------------------------------");
                    println!(" ");
                    let user_id=req.get_session().get::<u32>("userId").unwrap();
                    if user_id.is_none() {
                        //println!("{:?}", user_id);
                    }
                }
                srv.call(req).map(|res| res)
            })
            .service(scope)
            .default_service(resource("").route(get().to(login::action::into_404)))
    })
    .bind("127.0.0.1:8181")?
    .run()
    .await
}
